# src/service/auth_service.py
from src.db.user_db import get_user_by_username, create_user
from src.utils.password import hash_password, verify_password
from src.utils.logger import get_logger

logger = get_logger(__name__)

def register_user(
    username: str,
    password: str,
    real_name: str,
    contact_info: str,
    address: str = "",
    user_role: str = "买家"
) -> tuple[bool, str]:
    """
    用户注册业务逻辑
    返回：(是否成功, 提示信息)
    """
    # 1. 基础参数校验
    if not all([username, password, real_name, contact_info]):
        logger.warning("注册参数缺失")
        return False, "缺少必填字段（用户名、密码、真实姓名、联系方式）"
    
    if len(password) < 6:
        logger.warning(f"密码长度不足（username: {username}）")
        return False, "密码长度不能少于6位"
    
    # 2. 加密密码并创建用户
    hashed_pwd = hash_password(password)
    success = create_user(
        username=username,
        hashed_password=hashed_pwd,
        real_name=real_name,
        contact_info=contact_info,
        address=address,
        user_role=user_role
    )
    
    if success:
        return True, "注册成功，等待审核"
    else:
        return False, "用户名已存在或注册失败"

def login_user(username: str, password: str) -> tuple[bool, dict | str]:
    """
    用户登录业务逻辑
    返回：(是否成功, 用户信息字典/错误提示)
    """
    # 1. 查询用户
    user = get_user_by_username(username)
    if not user:
        logger.warning(f"登录用户不存在（username: {username}）")
        return False, "用户名或密码错误"
    
    # 2. 验证密码
    if not verify_password(password, user["password"]):
        logger.warning(f"登录密码错误（username: {username}）")
        return False, "用户名或密码错误"
    
    # 3. 登录成功，返回用户信息（剔除密码字段）
    user_info = user.copy()
    user_info.pop("password")  # 敏感信息不返回
    logger.info(f"用户登录成功（username: {username}）")
    return True, user_info